package com.sunwayworld.baseline.feishu.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sunwayworld.baseline.feishu.config.FeishuLoginConfig;
import com.sunwayworld.baseline.feishu.service.FeishuAuthCheckService;
import com.sunwayworld.baseline.feishu.util.FeishuCheckUtils;
import com.sunwayworld.cloud.module.mobile.utils.HttpUtils;
import com.sunwayworld.framework.context.LocalContextHelper;
import com.sunwayworld.framework.exception.InvalidDataException;
import com.sunwayworld.framework.mybatis.mapper.MatchPattern;
import com.sunwayworld.framework.mybatis.mapper.SearchFilter;
import com.sunwayworld.framework.spring.annotation.GikamBean;
import com.sunwayworld.framework.utils.StringUtils;
import com.sunwayworld.module.mdm.user.bean.CoreUserBean;
import com.sunwayworld.module.mdm.user.service.CoreUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.web.client.RestTemplate;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName FeishuAuthCheckServiceImpl
 * @Author zhoujq
 * @Date 2022/8/4
 * @Version 1.0
 **/
@Repository
@GikamBean
public class FeishuAuthCheckServiceImpl implements FeishuAuthCheckService {

    // 以下为测试应用码
//    private static final String CLIENT_ID = "cli_a26137f147f8d013";
//    private static final String CLIENT_SECRET = "IlXSXm7qOGhAb2krsBt6GgxqL4yK3c4J";
//    // 重定向地址，校验token会用到  暂时填的测试地址
//    private static final String REDIRECT_URI = "http://172.16.31.98:8094/feishu/login-check";

    // 以下为客户提供的应用码
//    private static final String CLIENT_ID = "cli_a25bb3bd0d7a500b";
//    private static final String CLIENT_SECRET = "LiNoD3fO7AFPAtWMT9jeGrntx5jfIKqA";
//    private static final String REDIRECT_URI = "http://180.184.78.55:8080/feishu/login-check";

    // 改为从配置文件读取
    @Autowired
    private FeishuLoginConfig feishuLoginConfig;

    @Autowired
    CoreUserService coreUserService;

    @Override
    public String feishuLoginCheck(String code, String state) {

        try {
//            String tokenUrl = "https://passport.feishu.cn/suite/passport/oauth/token";
            JSONObject res = new JSONObject();

            res.put("grant_type", "authorization_code");
            res.put("client_id", feishuLoginConfig.getClient_id());
            res.put("client_secret", feishuLoginConfig.getClient_secret());
            res.put("code", code);
            res.put("redirect_uri", feishuLoginConfig.getLogin_url());

            RestTemplate restTemplate = FeishuCheckUtils.getInstance().restTemplate();
            JSONObject resp = restTemplate.postForObject(feishuLoginConfig.getToken_url(), res, JSONObject.class);

            String access_token = resp.getString("access_token");

//            String userDataUrl = "https://passport.feishu.cn/suite/passport/oauth/userinfo";
            Map<String, String> headers = new ConcurrentHashMap<>();
            headers.put("Authorization", "Bearer ".concat(access_token));

            String userDataString = HttpUtils.get(feishuLoginConfig.getUser_data_url(), headers);
            JSONObject userData = JSONObject.parseObject(userDataString);

            CoreUserBean userBean = null;
            String union_id = userData.getString("union_id");
            if (!StringUtils.isBlank(union_id)) {
                userBean = coreUserService.selectFirstByFilter(SearchFilter.instance().match("feishuNumber", union_id).filter(MatchPattern.EQ));
            }
            if (userBean == null) {
                throw new InvalidDataException("对应用户未找到");
            } else {
                return "redirect:/?loginType=eisso&userId=".concat(userBean.getId()).concat("&password=").concat(userBean.getPassword());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new InvalidDataException("用户数据校验失败");
        }
    }

    @Override
    public String bindFeishuAccount(String code, String state) {
        try {
//            String tokenUrl = "https://passport.feishu.cn/suite/passport/oauth/token";
            JSONObject res = new JSONObject();

//            final String BIND_FEiSHU_URI = "http://180.184.78.55:8080/feishu/bind-feishu-account";

            res.put("grant_type", "authorization_code");
            res.put("client_id", feishuLoginConfig.getClient_id());
            res.put("client_secret", feishuLoginConfig.getClient_secret());
            res.put("code", code);
            res.put("redirect_uri", feishuLoginConfig.getBind_feishu_url());

            RestTemplate restTemplate = FeishuCheckUtils.getInstance().restTemplate();
            JSONObject resp = restTemplate.postForObject(feishuLoginConfig.getToken_url(), res, JSONObject.class);

            String access_token = resp.getString("access_token");

//            String userDataUrl = "https://passport.feishu.cn/suite/passport/oauth/userinfo";
            Map<String, String> headers = new ConcurrentHashMap<>();
            headers.put("Authorization", "Bearer ".concat(access_token));

            String userDataString = HttpUtils.get(feishuLoginConfig.getUser_data_url(), headers);
            JSONObject userData = JSONObject.parseObject(userDataString);

            String union_id = userData.getString("union_id");
            String userId = LocalContextHelper.getLoginUserId();
            if (!StringUtils.isBlank(userId)) {
                CoreUserBean userBean = coreUserService.selectFirstByFilter(SearchFilter.instance().match("id", userId).filter(MatchPattern.EQ));
                userBean.setExt$Item("feishuNumber", union_id);
                coreUserService.getDao().update(userBean, "feishuNumber");
            }
            return "redirect:/";
        } catch (Exception e) {
            e.printStackTrace();
            throw new InvalidDataException("用户数据校验失败");
        }
    }

    @Override
    public JSONObject getFeishuLoginConfig() {
        JSONObject req = new JSONObject();

        String gotoUrl = "https://passport.feishu.cn/suite/passport/oauth/authorize"
                .concat("?client_id=").concat(feishuLoginConfig.getClient_id())
                .concat("&redirect_uri=").concat(feishuLoginConfig.getLogin_url())
                .concat("&response_type=code&state=first");

        req.put("goto", gotoUrl);

        String homeUrl = feishuLoginConfig.getHome_url();
        req.put("homeUrl", homeUrl);

        String bindPage = "https://passport.feishu.cn/suite/passport/oauth/authorize"
                .concat("?client_id=").concat(feishuLoginConfig.getClient_id())
                .concat("&redirect_uri=").concat(feishuLoginConfig.getBind_feishu_url())
                .concat("&response_type=code&state=first");
        req.put("bindPage", bindPage);
        return req;
    }
}
